//
//  SqlManager.swift
//  edu
//
//  Created by karlzhou on 15/11/25.
//  Copyright © 2015年 karlzhou. All rights reserved.
//

import UIKit
//import FMDB
class SqlManager {
    
    
    
    static let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0].stringByAppendingString("/FilmCollection.sqlite")
    
    private static var db:FMDatabase!
    
    static func insertHotSearch(words:HotSearchModel) -> Void {
        
        db = FMDatabase(path: path)
        
        if(!db.open() ){
            return
        }
        
        if db.tableExists("HotSearch"){
            if !db.executeUpdate("insert into HotSearch(times,word) values(?,?)", withArgumentsInArray:[words.times!,words.words!]){
                print("insert error")
            }
        }else{
            self.createHotSearchTable(db)
        }
        
        db.close()
        
        
    }
    
    
    static func createHotSearchTable(db1:FMDatabase){
        
        if(!db1.open() ){
            return
        }
        
        if !db1.executeUpdate("create table HotSearch(times int, word varchar(10))",withArgumentsInArray:nil){
            
            print("create HotSearch table fail ")
        }
        db1.close()
    }
    
    static func getHotSearchWords() -> [HotSearchModel]{
        db = FMDatabase(path: path)
        var words :[HotSearchModel] = []
        if(!db.open() ){
            return words
        }
        
        if  let resultSet =  db.executeQuery("select * from HotSearch", withArgumentsInArray: nil) {
            while(resultSet.next()){
                let hs = HotSearchModel()
                
                hs.times =  resultSet.intForColumn("times") as? Int
                hs.words = resultSet.stringForColumn("word")
                words.append(hs)
            }
            
        }
        return words
    }
    
}
